package com.kob.backend;

import cn.hutool.core.io.IoUtil;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.InputStream;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class SerialReader {

    public static void main(String[] args) throws Exception {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM5");
        SerialPort serialPort = (SerialPort) portIdentifier.open("SerialReader", 2000);
        serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        InputStream input = serialPort.getInputStream();
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                try {
                    Scanner scanner = new Scanner(input);
                    while (scanner.hasNextLine()) {
                        String line = scanner.nextLine();
                        System.out.println(line);
                    }
                } catch (Exception e) {
                    System.err.println("从串口读取失败:" + e.getMessage());
                }
            }
        };

        // 每隔1秒执行一次任务x
        timer.scheduleAtFixedRate(task, 0, 1000);
    }
}
